﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordNet.Core;
using WordNet.Core.DataContract;
using WordNet.Core.ElementContracts;

namespace DataFileProvider
{
    public class ExceptionEntryMapper:IDataMapper<IExceptionEntry>
    {
        IDataProvider<IExceptionEntryProxy> _fpExceptionEntryProxy;
       
        public ExceptionEntryMapper(IDataProvider<IExceptionEntryProxy> provider)
        {
            _fpExceptionEntryProxy = provider;
        }
        
        public IEnumerable<IExceptionEntry> GetAll(WordNet.Core.POS pos)
        {
            if (pos == null)
                throw new ArgumentException();
            
            if (!_fpExceptionEntryProxy.IsOpen) _fpExceptionEntryProxy.Open();
            var content = ContentType<IExceptionEntryProxy>.GetExceptionContentType(pos);
            var parser = content.DataType.GetParser();
            IDataSource file = _fpExceptionEntryProxy.GetSourceForContentType(content);

            foreach (var entry in file.AllLines())
            {
                var entryObject = parser.Parse(entry);
                yield return new ExceptionEntry(entryObject, pos);
            }
        }

        public IExceptionEntry GetByKey(object key)
        {
            if (key == null || !(key is IExceptionEntryID))
                throw new ArgumentException();
            
            IExceptionEntryID id = (IExceptionEntryID)key;
            if (!_fpExceptionEntryProxy.IsOpen) _fpExceptionEntryProxy.Open();
            var content = ContentType<IExceptionEntryProxy>.GetExceptionContentType(id.PartOfSpeech);
            IDataSource file = _fpExceptionEntryProxy.GetSourceForContentType(content);

            String line = file.Search(id.SurfaceForm);

            if (line == null)
                return null;

            var proxy = content.DataType.GetParser().Parse(line);
            return new ExceptionEntry(proxy, id.PartOfSpeech);
        }

        public IExceptionEntry GetDefinition(string query)
        {
            throw new NotImplementedException();
        }

        public IDataProvider<IExceptionEntry> DataProvider { get { return (IDataProvider<IExceptionEntry>)_fpExceptionEntryProxy; } }
    }
}
